/*
 * CDataStore.cpp
 *
 *  Created on: 2018年5月11日
 *      Author: zhengboyuan
 */

#include "CDataStore.h"
#include "TStringUtil.h"
#include "TSafeStr.h"

static bool isEmpty(const char* str)
{
	return (str == NULL || strlen(str) == 0);
}

bool toObject(sqlite3_stmt* stmt, PersonFlowCount& record)
{
    int col = 0;

    col ++;
    record.enterNum = sqlite3_column_int(stmt, col ++);
    record.leaveNum = sqlite3_column_int(stmt, col ++);

    return true;
}

CDataStore::CDataStore()
{
}

CDataStore::~CDataStore()
{
}

bool CDataStore::open(const std::string& path)
{
	comn::AutoCritSec lock(m_cs);
    if (!m_store.open(path))
    {
        return false;
    }

    createTables();

    return true;
}

void CDataStore::close()
{
	comn::AutoCritSec lock(m_cs);
	m_store.close();
}

bool CDataStore::isOpen()
{
	comn::AutoCritSec lock(m_cs);
	return m_store.isOpen();
}

bool CDataStore::setFlowCount(const std::string& id, const PersonFlowCount& flowCount)
{
    std::ostringstream oss;
    oss << "replace into flow_count values(";
    oss << "'" << id << "'";
    oss << "," << flowCount.enterNum;
    oss << "," << flowCount.leaveNum;
    oss << ")";

    std::string sql = oss.str();
    return update(sql) > 0;
}

bool CDataStore::removeFlowCount(const std::string& id)
{
    std::string sql = comn::StringUtil::format("delete from flow_count where id='%s'", id.c_str());
    return execute(sql);
}

bool CDataStore::getFlowCount(const std::string& id, PersonFlowCount& flowCount)
{
    std::ostringstream oss;
    oss << "select * from flow_count where id='" << id << "'";
    std::string sql = oss.str();
    return queryObject(sql, flowCount);
}

bool CDataStore::execute(const std::string& sql)
{
	comn::AutoCritSec lock(m_cs);
	return m_store.execute(sql);
}

bool CDataStore::query(const std::string& sql, std::string& value)
{
	comn::AutoCritSec lock(m_cs);
	return m_store.query(sql, value);
}

bool CDataStore::query(const std::string& sql, int& value)
{
	comn::AutoCritSec lock(m_cs);
	return m_store.query(sql, value);
}

int CDataStore::update(const std::string& sql)
{
	comn::AutoCritSec lock(m_cs);
	return m_store.update(sql);
}


int CDataStore::queryInt(const std::string& sql, int defValue)
{
	comn::AutoCritSec lock(m_cs);
    return m_store.queryInt(sql, defValue);
}

bool CDataStore::insert(const std::string& sql, int& autoId)
{
	comn::AutoCritSec lock(m_cs);
	return m_store.insert(sql, autoId);
}

bool CDataStore::insert(const std::string& sql, int64_t& autoId)
{
	comn::AutoCritSec lock(m_cs);
	return m_store.insert(sql, autoId);
}


void CDataStore::createTables()
{
    const char* sqlFlow =
        "CREATE TABLE if not exists flow_count("\
        "ID VARCHAR(45) NOT NULL PRIMARY KEY,"\
        "ENTER INTEGER NOT NULL,"\
        "LEAVE INTEGER NOT NULL"\
        ");";

    execute(sqlFlow);
}